package com.soft.line.controller;


import com.soft.line.service.RoleInfoService;
import com.soft.line.service.UserInfoService;
import com.soft.line.util.exception.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(description = "角色接口")
@Slf4j
@RestController
@RequestMapping("/systemAdmin")
public class RoleInfoController {

    @Autowired
    private RoleInfoService roleInfoService;
    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/roles")
    @ApiOperation(value = "获取所有角色列表")
    public CommonResult getAllMenus(@RequestBody Map<String,Object> map) {
        return CommonResult.success(roleInfoService.selectAllRoleMenuInfo(map));
    }

    @DeleteMapping("/role")
    @ApiOperation(value = "删除角色")
    public CommonResult deleteRole(@RequestBody Map<String,Object> map) {
        roleInfoService.delete(map);
        return CommonResult.success("删除成功");
    }

    @PostMapping("/role")
    @ApiOperation(value = "保存角色")
    public CommonResult saveRole(@RequestBody Map<String,Object> map) {
        if (map.get("roleName")==null||"".equals(map.get("roleName"))){
            return CommonResult.success("角色名称不能为空","角色名称不能为空");
        }else if(roleInfoService.countRoleName((Integer)map.get("id"),(String)map.get("roleName")) > 0){
            return CommonResult.success("角色名称已存在","角色名称不能为空");
        }
        if (map.get("id")==null){
            //添加
            roleInfoService.add(map);
            return CommonResult.success("添加成功");
        }else{
            //修改
            if (userInfoService.countByRoleId((Integer) map.get("id"))>0 && !map.get("state").equals("1")){
                return CommonResult.success("该角色已有用户使用，无法被禁用","该角色已有用户使用，无法被禁用");
            }else{
                roleInfoService.update(map);
                return CommonResult.success("修改成功");
            }
        }
    }
}
